package com.example.demo.controller;

import com.example.demo.bean.Indent;
import com.example.demo.bean.Information;
import com.example.demo.bean.Tag;
import com.example.demo.bean.User;
import com.example.demo.service.IndentService;
import com.example.demo.service.InformationService;
import com.example.demo.service.TagService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.jws.soap.SOAPBinding;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by yanmaoyuan on 2018/4/16.
 */
@RestController
@RequestMapping(value = "/information")
public class InformationController {

    @Autowired
    private InformationService informationService;

    @Autowired
    private UserService userService;

    @Autowired
    private TagService tagService;

    @Autowired
    private IndentService indentService;

    //根据informationId获取一条信息
    @GetMapping(value = "/getOne")
    //判断信息是否已经在收藏列表(0:false 1:true)
    //判断信息是否本人发布(0:false 1:true)
    public HashMap<String, Object> findInformation(@RequestParam(value = "informationId") String informationId, @RequestParam(value ="userId") String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        int isMyCollection = 0;
        int isMyRelease = 0;
        Information information = informationService.getInformationById(informationId);
        User user = userService.getUserById(userId);
        if(information.getUserId().equals(userId)){
            isMyRelease = 1;
        }
        List<Information> collections = user.getCollects();
        for(Information data : collections){
            if(data.getInformationId().equals(informationId)){
                isMyCollection = 1;
            }
        }
        if(information != null){
            hashMap.put("status", "success");
            hashMap.put("information", information);
            hashMap.put("isMyCollection", isMyCollection);
            hashMap.put("isMyRelease", isMyRelease);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //撤销发布
    @PostMapping(value = "/deleteInformation")
    public void deleteInformation(@RequestParam(value = "informationId") String informationId) {
        Information information = informationService.getInformationById(informationId);
        List<User> users = information.getUsers();
        for (User user : users) {
            List<Information> collects = user.getCollects();
            collects.remove(information);
            user.setCollects(collects);
        }
        List<Indent> indents = indentService.getIndentByInformationId(informationId);
        for (Indent indent : indents) {
            String indentId = indent.getIndentId();
            indentService.deleteIndent(indentId);
        }
        informationService.deleteInformation(informationId);
    }

    //添加一条信息
    @PostMapping(value = "/add")
    public HashMap<String, Object> addInformation(@RequestParam(value = "userId") String userId, @RequestParam(value = "title") String title, @RequestParam(value = "location") String location,
                                                  @RequestParam(value = "tagId") String tagId, @RequestParam(value = "price") double price,@RequestParam(value = "imgUrl") String imgUrl,
                                                  @RequestParam(value = "deadline") String deadline, @RequestParam(value = "description") String description) throws ParseException{
        HashMap<String, Object> hashMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = sdf.parse(deadline);
        Tag tag = tagService.getTagById(tagId);
        List<Tag> tags = new ArrayList<>();
        tags.add(tag);
        Information information=new Information(userId,title,location,tags,price,date,description);
        information.setImageUrl(imgUrl);
        if(information != null){
            hashMap.put("status", "success");
            informationService.addInformation(information);
            hashMap.put("informationId", information.getInformationId());
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //获取所有有效信息
    @GetMapping(value = "/getAllAvailable")
    public HashMap<String, Object> getAvailableInformation(@RequestParam(value = "userId") String myUserId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<HashMap<String, Object>> list = new ArrayList<>();
        User myUser = userService.getUserById(myUserId);
        List<Information> informations = informationService.getInformationAvailable();
        for(Information information : informations){
            int isMyCollection = 0;
            int isMyRelease = 0;
            if(information.getUserId().equals(myUserId)){
                isMyRelease = 1;
            }
            List<Information> collections = myUser.getCollects();
            for(Information data : collections){
                if(data.equals(information)){
                    isMyCollection = 1;
                }
            }
            HashMap<String, Object> map1 = new HashMap<>();
            String userId = information.getUserId();
            User user = userService.getUserById(userId);
            map1.put("user", user);
            map1.put("information", information);
            map1.put("isMyCollection", isMyCollection);
            map1.put("isMyRelease", isMyRelease);
            list.add(map1);
        }
        if(list != null){
            hashMap.put("status", "success");
            hashMap.put("informations", list);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

//    //获取所有有效信息
//    @GetMapping(value = "/getAllAvailable")
//    public HashMap<String, Object> getAvailableInformation() {
//        HashMap<String, Object> hashMap = new HashMap<>();
//        List<HashMap<String, Object>> list = new ArrayList<>();
//        List<Information> informations = informationService.getInformationAvailable();
//        for(Information information : informations){
//            HashMap<String, Object> map1 = new HashMap<>();
//            String userId = information.getUserId();
//            User user = userService.getUserById(userId);
//            map1.put("user", user);
//            map1.put("information", information);
//            list.add(map1);
//        }
//        if(list != null){
//            hashMap.put("status", "success");
//            hashMap.put("informations", list);
//        }else{
//            hashMap.put("status", "failure");
//        }
//        return hashMap;
//    }

    //根据标签以及地点筛选信息
    @GetMapping(value = "/screen")
    public HashMap<String, Object> screenInformation(@RequestParam("location") String location, @RequestParam("tagId") String tagId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<Tag> tags = new ArrayList<>();
        Tag tag = tagService.getTagById(tagId);
        tags.add(tag);
//        for(String tagId : tagIds){
//            Tag tag = tagService.getTagById(tagId);
//            tags.add(tag);
//        }
        List<Information> informations = informationService.getInformationByCondition(location, tags);
        for(Information information : informations){
            HashMap<String, Object> map1 = new HashMap<>();
            String userId = information.getUserId();
            User user = userService.getUserById(userId);
            map1.put("user", user);
            map1.put("information", information);
            list.add(map1);
        }
        if(list != null){
            hashMap.put("status", "success");
            hashMap.put("informations", informations);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //更新信息状态
    @PostMapping(value = "/modify")
    public HashMap<String, Object> modifyInformation(@RequestParam(value = "informationId") String informationId, @RequestParam(value = "status") String status) {
        HashMap<String, Object> hashMap = new HashMap<>();
        Information information = informationService.getInformationById(informationId);
        information.setStatus(status);
        informationService.addInformation(information);
        if(information != null){
            hashMap.put("status", "success");
            hashMap.put("informationId", informationId);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //通过用户查询所有有效信息
    @GetMapping(value = "/getAvailableByUser")
    public HashMap<String, Object> getAvailableByUser(@RequestParam(value = "userId") String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        int isMyCollection = 0;
        int isMyRelease = 0;
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<Information> informations = informationService.getAvailableByUser(userId);
        for (Information information : informations){
            HashMap<String, Object> map1 = new HashMap<>();
            User user = userService.getUserById(userId);
            map1.put("user", user);
            map1.put("information", information);
            list.add(map1);
        }
        if(list != null){
            hashMap.put("status", "success");
            hashMap.put("informations", informations);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    //更改信息是否删除
    @PostMapping(value = "/modifyIsDelete")
    public HashMap<String, Object> modifyIsDelete(@RequestParam(value = "informationId") String informationId, @RequestParam(value = "type") int type) {
        HashMap<String, Object> hashMap = new HashMap<>();
        Information information = informationService.getInformationById(informationId);
        information.setIsDelete(type);
        informationService.addInformation(information);
        if(information != null){
            hashMap.put("status", "success");
            hashMap.put("informationId", informationId);
        }else{
            hashMap.put("status", "failure");
        }
        return hashMap;
    }

    @RequestMapping(value = "/upload", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String upload(@RequestParam(value = "userId") String userId, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest req=(MultipartHttpServletRequest)request;
        MultipartFile file=req.getFile("file");
        if (file.isEmpty()) {
            return "所选图像文件为空";
        }
        // 获取文件名
        String fileName = userId+file.getOriginalFilename();
        //获取文件大小
        int size=(int)file.getSize();
        System.out.println(fileName+"-->"+size);
        // 获取文件的后缀名
        // String suffixName = fileName.substring(fileName.lastIndexOf("."));
        File directory=new File("");
//        // 文件上传后的路径
//        String filePath = directory.getCanonicalPath();

//        String rootPath = System.getProperty("user.dir");

        //File dest = new File("/home/file/user/"+ fileName);
        File dest = new File("/home/file/information/"+ fileName);
        try {
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            System.out.println("上传成功");
//            return "/home/file/"+ fileName;
            return "http://120.77.247.244:8080/information/" + fileName;
//            return "http://120.77.247.244:8080/user/" + fileName;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}